package com.raorao.config.service.process;

import java.text.MessageFormat;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.raorao.config.controller.Model.ResponseEntity;
import com.raorao.config.controller.exception.ServiceException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ControllerAdvice;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.method.HandlerMethod;


/**
 * @author raorao
 * @version 1.0
 * @description: 全局异常处理
 * @date 2021/11/30 16:25
 */
@ControllerAdvice
public class GlobalExceptionHandler {

    private static final Logger logger = LoggerFactory.getLogger(GlobalExceptionHandler.class);


    @ExceptionHandler(value = Exception.class)
    @ResponseBody
    public ResponseEntity<?> handle(HttpServletRequest request, HttpServletResponse response,
                                    Object handler, Exception ex) {
        String className = GlobalExceptionHandler.class.getName();
        String methodName = "afterCompletion";
        if (handler instanceof HandlerMethod) {
            HandlerMethod m = (HandlerMethod) handler;
            className = m.getBeanType().getName();
            methodName = m.getMethod().getName();
        }

        logger.error(MessageFormat.format("{0}.{1} RESTFUL({2}) METHOD({3}) Error, Exception : {4}", className, methodName, request.getRequestURI(), request.getMethod(), ex.getMessage()));

        try {
            if(ex instanceof ServiceException){
                logger.error("	ServiceException. ", ex);
                ResponseEntity<?> responseEntity = ResponseEntity.error(ex.getMessage());
                ResponseHandler.response(response, responseEntity);
            }
            else if (ex instanceof MethodArgumentNotValidException) {
                BindingResult bindingResult = ((MethodArgumentNotValidException) ex).getBindingResult();
                String errorMesssage = "参数校验错误:";
                for (FieldError fieldError : bindingResult.getFieldErrors()) {
                    errorMesssage += fieldError.getDefaultMessage();
                    break;
                }
                ResponseEntity<?> responseEntity = ResponseEntity.fail(40000, errorMesssage);
                ResponseHandler.response(response, responseEntity);
            } else {
                logger.error("	unknown Exception. ", ex);
                ResponseEntity<?> responseEntity = ResponseEntity.error(ex.getMessage());
                ResponseHandler.response(response, responseEntity);
            }
        } catch (Exception e) {
            logger.error("OverallExceptionResolver Handler Exception Error." + e);
        }

        return null;
    }
}
